package org.msfj.common.feign;

import feign.FeignException;
import feign.Response;
import org.msfj.common.exception.BusinessException;
import org.msfj.common.model.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * @Description:
 * @Author: like
 * @Date: 2018-01-18 18:13
 * @Version: 1.0
 * @Created in idea by autoCode
 */
@Component
@ConditionalOnClass(SpringDecoder.class)
public class FeignResponseDecoder extends SpringDecoder {
    Logger logger = LoggerFactory.getLogger(getClass());

    public FeignResponseDecoder(ObjectFactory<HttpMessageConverters> messageConverters) {
        super(messageConverters);
    }

    @Override
    public Object decode(Response response, Type type) throws IOException, FeignException {
        if(response.status() >= 400 && response.status() <= 499){
            throw new BusinessException("服务访问异常");
        }else{
            CommonResult result = (CommonResult) super.decode(response, type);
            if (result.getHttpCode() == 200) {
                return result;
            } else {
                throw new BusinessException(result.getMsg());
            }
        }
    }
}
